<template>
  <div style="min-width: 829px">
    <div v-if="$route.path == '/projectAdmin/shopList' || $route.path == '/projectAdmin/shopLists' || $route.path == '/shopList'">
      <div class="vs-search-box">
        <el-form ref="form" :inline="true" :model="paging" label-width="110px">
          <el-form-item label="门店:">
            <el-input style="width: 200px" v-model="paging.title"></el-input>
          </el-form-item>
          <el-form-item label="门店分类:">
            <el-select v-model="paging.cate_id" clearable style="width:200px" placeholder="请选择">
                <el-option
                    v-for="item in cateData"
                    :key="item.id"
                    :label="item.title"
                    :value="item.id">
                </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="负责人姓名">
            <el-input style="width: 200px" v-model="paging.name"></el-input>
          </el-form-item>
          <el-form-item label="添加人">
            <el-input style="width: 200px" v-model="paging.admin_name"></el-input>
          </el-form-item>
          <el-form-item label="" class="vs-right-btns">
            <el-button @click="reset">重置</el-button>
            <el-button @click="select(1)" type="primary">查询</el-button>
          </el-form-item>
          <el-form-item label="联系电话">
            <el-input style="width: 200px" v-model="paging.tel"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <div class="vs-table-box">
        <div class="operation-box clear-float">
          <el-button
            icon="el-icon-plus"
            @click="utils.goUrl(`/editShop?title=新增门店`)"
            style="margin-left: auto"
            type="primary"
          >
            新增
          </el-button>
        </div>
        <el-table
          v-loading="loading"
          :data="tableData"
          header-row-class-name="has-gutter-table"
          style="width: 100%"
        >
          <el-table-column label="门店名称" prop="title">
            <template slot-scope="scope">
              <span class="shopCs" @click="toShop(scope.row)">{{ scope.row.title }} </span>
            </template>
          </el-table-column>
          <el-table-column prop="position" label="位置"> </el-table-column>
          <el-table-column prop="parking" label="停车推荐"> </el-table-column>
          <el-table-column label="门店图片">
            <template slot-scope="scope">
              <el-image
                class="image-thumbnail"
                :src="scope.row.images[0]"
                fit="cover"
                :preview-src-list="scope.row.images"
              >
              </el-image>
            </template>
          </el-table-column>
          <el-table-column label="营业时间">
            <template slot-scope="scope">
              <span>{{ scope.row.start_time }} - {{ scope.row.end_time }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="name" label="负责人姓名"> </el-table-column>
          <el-table-column prop="admin.realname" label="添加人"> </el-table-column>
          <el-table-column prop="cate_id" label="分类名称">
            <template slot-scope="scope">
              {{getStoreCateNum(scope.row.cate_id)}}
            </template>
          </el-table-column>
          <el-table-column prop="tel" label="联系电话"> </el-table-column>
          <el-table-column prop="tel" label="状态">
            <template slot-scope="scope">
              {{ scope.row.status == 1 ? "营业中" : "暂停营业" }}
            </template>
          </el-table-column>
          <el-table-column prop="expire" label="到期时间"> </el-table-column>
          <el-table-column prop="tel" label="小程序配置">
            <template slot-scope="scope" v-if="scope.row.storeConfig">
              <div>appid : {{scope.row.storeConfig.wx_app_id}}</div>
              <div>秘钥 : {{scope.row.storeConfig.wx_app_secret}}</div>
            </template>
          </el-table-column>
          <el-table-column prop="tel" label="品牌">
            <template slot-scope="scope" v-if="scope.row.brand">
              <div>{{scope.row.brand.brand}}</div>
              <!-- <div>
                <el-image
                class="image-thumbnail"
                :src="scope.row.brand.img"
                fit="cover"
                :preview-src-list="[scope.row.brand.img]"
              >
              </el-image></div>
              <div>{{scope.row.brand.desc}}</div> -->
            </template>
          </el-table-column>
          <el-table-column fixed="right" width="109" label="操作">
            <template slot-scope="scope">
              <span @click="menuFun(scope.row)" class="tab-table-text">菜单权限</span>
              <span @click="setRow(4, scope.row)" class="tab-table-text">小程序配置</span>
              <span @click="setRow(1, scope.row)" class="tab-table-text">编辑</span>
              <span @click="setRow(9, scope.row)" v-if="scope.row.brand_id < 1" class="tab-table-text">设为品牌</span>
              <!-- <span @click="setRow(2, scope.row)" class="tab-table-text">免单人管理</span> -->
              <span @click="setRow(3,scope.row)" class="tab-red-text">删除</span>
              <span @click="qeCode(scope.row)" class="tab-table-text">查看二维码</span>
            </template>
          </el-table-column>
        </el-table>
        <div class="vs-paging-box">
          <el-pagination
            @current-change="handleCurrentChange"
            :current-page.sync="paging.page"
            :page-size="paging.limit"
            layout="prev, pager, next, jumper"
            :total="paging.total"
          >
          </el-pagination>
        </div>
      </div>
    </div>

    <el-dialog title="小程序配置" :visible.sync="dialogFormVisible" :close-on-click-modal="false" :show-close="false">
      <el-form :model="form" ref="ruleForm" :rules="rules">
        <el-form-item label="微信小程序appid" prop="wx_app_id" label-width="190px">
          <el-input v-model="form.wx_app_id" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="微信小程序秘钥" prop="wx_app_secret" label-width="190px">
          <el-input v-model="form.wx_app_secret" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogForm()">取 消</el-button>
        <el-button type="primary" @click="dialogFormFun('ruleForm')">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="品牌" :visible.sync="trademarkVisible" :close-on-click-modal="false" :show-close="false">
      <el-form :model="trademark" ref="ruleForms" :rules="trademarkRules">
        <el-form-item label="品牌名称" prop="brand" label-width="190px">
          <el-input v-model="trademark.brand" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="品牌图片" prop="img" label-width="190px">
          <VsUploading
            width="120px"
            @verify="verify('images',$event)"
            v-model="trademark.img"></VsUploading>
        </el-form-item>
        <el-form-item label="品牌说明" prop="desc" label-width="190px">
          <el-input v-model="trademark.desc" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="trademarkVisibleForm()">取 消</el-button>
        <el-button type="primary" @click="trademarkVisibleFormFun('ruleForms')">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog
        title="菜单权限配置"
        :visible.sync="dialogVisible"
        width="700px"
        
        :before-close="handleClose">
        <el-form :model="jurisdictionForm" :rules="rules" ref="jurisdictionForm" label-width="160px" class="demo-ruleForm" >
            <el-form-item label="菜单类型：" prop="title">
                <el-radio-group v-model="jurisdictionForm.menu_type">
                  <el-radio label="1">分类菜单</el-radio>
                  <el-radio label="2">自定义菜单</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="自定义菜单：" v-if="jurisdictionForm.menu_type == 2" prop="menu_ids" :rules="[
              { required: true, message: '请选择自定义菜单', trigger: 'blur' },
            ]">
                <el-cascader
                    v-model="jurisdictionForm.menu_ids"
                    :options="menuList"
                    :props="props"
                    collapse-tags
                    clearable
                    ref="cascader"
                    @change="handleChange"
                    placeholder="请选择"></el-cascader>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="handleClose()">取 消</el-button>
            <el-button type="primary" :loading="isBtn" @click="setAd">确 定</el-button>
        </span>
    </el-dialog>

    <el-dialog
        title="二维码"
        :visible.sync="qrcodeVisible"
        width="30%"
        :before-close="qrcodeClose">
        <div style="text-align: center;">
            <img :src="qrImg" alt="">
            <div class="plImg" @click="upImg()">下载二维码</div>
        </div>
    </el-dialog>

    <router-view></router-view>
  </div>
</template>

<script>
import VsUploading from '../../components/VsUploading'
export default {
  components:{
      VsUploading
  },
  data() {
    return {
      qrcodeVisible: false,
      props: { multiple: true, emitPath: false, value: 'id', label: 'title', children: 'child' },
      menuList: [],
      jurisdictionForm: {
        store_id: '',
        menu_type: '1',
        menu_ids: []
      },
      isBtn: false,
      dialogVisible: false,
      loading: false,
      paging: {
        title: "",
        name: "",
        tel: "",
        admin_name: "",
        page: 1,
        cate_id: '',
        limit: 10,
        total: 0, //总数
      },
      rules: {
          wx_app_id: [
            { required: true, message: '请输入微信小程序appid', trigger: 'blur' },
          ],
          wx_app_secret: [
            { required: true, message: '请选择微信小程序秘钥', trigger: 'blur' }
          ],
      },
      trademarkRules: {
          brand: [
            { required: true, message: '请输入品牌名称', trigger: 'blur' },
          ],
          img: [
            { required: true, message: '请选择品牌图片', trigger: 'blur' }
          ],
      },
      form: {
        wx_app_id: '',
        wx_app_secret: ''
      },
      trademark: {
        brand: '',
        img: '',
        desc: '',
        store_id: ''
      },
      tableData: [],
      getStoreCateData: [],
      dialogFormVisible: false,
      trademarkVisible: false,
      rowItem: {},
      cateData: [],
      qrImg: '',
      filename: ''
    };
  },
  created() {
    // 获取菜单参数 customize_id
    let menu = JSON.parse(localStorage.getItem('menu'))
    this.uniqueStair = localStorage.getItem('uniqueStair') // 子级
    this.uniqueSublevel = localStorage.getItem('uniqueSublevel') // 父级
    console.log(767, this.uniqueStair, this.uniqueSublevel)
    menu.forEach(item => {
      if(item.title === this.uniqueSublevel) {
        localStorage.setItem('customize_id', item.customize_id || '')
      }
    });

    this.GetList();
    this.getStoreCate()
    this.GetcateList()
    this.getMenu()
  },
  methods: {
    upImg() {
      const a = document.createElement('a');
      a.href = this.qrImg;
      a.download = this.filename+'二维码' || 'image.png';
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
    },
    qrcodeClose() {
        this.qrcodeVisible = false
        this.qrImg = ''
    },
    async qeCode(row) {
      this.filename = row.title
        this.loading = true
        let {code,data} = await this.$Http.getStoreQr({store_id:row.id});
        this.loading = false
        if(code){
            this.qrcodeVisible = true
            this.qrImg = data
        }
      },
     handleChange(value) {
        const checkedNodes = this.$refs.cascader.getCheckedNodes();
        const allIds = new Set();
        checkedNodes.forEach(node => {
            allIds.add(node.value)
            // 添加当前节点路径上的所有ID
            node.children.forEach(item => allIds.add(item.value));
        });
        
        // this.allSelectedIds = Array.from(allIds);
        this.jurisdictionForm.menu_ids = Array.from(allIds)
        console.log('所有选中的ID（包含父级）:', this.jurisdictionForm.menu_ids);
    },
    setAd() {
      this.$refs['jurisdictionForm'].validate(async valid => {
            if(!valid)return;
            this.isBtn = true;

            let pls = JSON.parse(JSON.stringify(this.jurisdictionForm))
            if (pls.menu_ids.length > 0) pls.menu_ids = pls.menu_ids.join()
            
            let obj = Object.assign({},pls);
            let {code,data} = await this.$Http.storeMenu(obj);
            this.isBtn = false;
            if(code){
                this.$message.success("保存成功!");
                this.dialogVisible = false;
                this.handleClose()
                this.GetList()
            }
        })
    },
    async getMenu(){
        let {code,data} = await this.$Http.getMenu();
        if(code){
            data.forEach(item => {
                if (item.child.length < 1) item.child = null
                item.child && item.child.forEach(row => {
                    if (row.child.length < 1) row.child = null
                })
            })
            this.menuList = data;
            console.log(66, this.menuList)
        }
    },
    menuFun(row) {
      let data = JSON.parse(JSON.stringify(row))
      this.jurisdictionForm.store_id = data.id
      this.jurisdictionForm.menu_type = data.menu_type+''
      this.jurisdictionForm.menu_ids = data.menu_ids ? data.menu_ids.split(',') : []

      this.dialogVisible = true
    },
    handleClose() {
      this.dialogVisible = false
    },
    // 获取分类列表
    async GetcateList() {
      let { code, data } = await this.$Http.getStoreCate({is_all: '1'});
      if (code) {
        this.cateData = data;
      }
    },
    toShop(row) {
      this.$confirm('跳转前请关闭，已打开的门店网站，避免数据有误。', '提示', {
        confirmButtonText: '跳转',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        window.open(row.store_url)
      })
    },
    verify(hasFmt,sta){
        if(sta){
            this.$refs[hasFmt].validate();
        }else this.$refs[hasFmt].clearValidate();
    },
    dialogForm() {
      this.form.wx_app_id = ''
      this.form.wx_app_secret = ''
      this.$refs['ruleForm'].resetFields();
      this.dialogFormVisible = false
    },
    dialogFormFun(formName) {
      this.$refs[formName].validate(async (valid) => {
          if (valid) {
            
            let { code, data } = await this.$Http.setConfig({ 
              store_id:this.rowItem.id,
              wx_app_id: this.form.wx_app_id,
              wx_app_secret: this.form.wx_app_secret,
             });
            if (code) {
              this.utils.message("配置成功");
              this.dialogFormVisible = false
              this.GetList();
            }
          }
        });
    },
    getStoreCateNum(params) {
      const matchedItem = this.getStoreCateData.find(item => item.id === params);
      return matchedItem ? matchedItem.title : ''; // 如果没有匹配到，返回空字符串
    },
    // 获取门店分类
    async getStoreCate() {
        let { code, data } = await this.$Http.getStoreCate({ is_all: 1 });
        if (code) {
            this.getStoreCateData = data
            console.log(11, this.getStoreCateData)
        }
    },
    handleCurrentChange(val) {
      this.paging.page = val;
      this.GetList();
    },
    // 查询
    select() {
      // if (!this.paging.title && !this.paging.name && !this.paging.tel && !this.paging.cate_id) {
      //   this.utils.message("查询条件至少输入一项！");
      //   return false;
      // }
      this.GetList();
    },
    trademarkVisibleForm(formName) {
      this.trademark.brand = ''
      this.trademark.img = ''
      this.trademark.desc = ''
      this.trademark.store_id = ''

      this.$refs['ruleForms'].resetFields();
      this.trademarkVisible = false
    },
    trademarkVisibleFormFun(formName) {
      this.$refs[formName].validate(async (valid) => {
          if (valid) {
              this.trademark.store_id = this.rowItem.id
              let {code,data} = await this.$Http.setStoreBrand(this.trademark)
                if(code){
                    this.$message.success('设置成功!');
                    this.handleCurrentChange(1);
                    this.trademarkVisible = false
                }
          }
        });
    },
    async setRow(type, row) {
      this.rowItem = row
        if (type == 1) {
            this.utils.goUrl(`/editShop?title=门店编辑&id=${row.id}`);
        }else if(type == 2) {
            this.utils.goUrl(`/freeofcharge?id=${row.id}`)
        }else if(type == 3){
            this.$msgbox({
                title: '提示',
                message: '确定要删除该门店吗?',
                type: 'warning',
                showCancelButton: true,
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                beforeClose:async (action, instance, done) => {
                    if (action === 'confirm') {
                    instance.confirmButtonLoading = true;
                    instance.confirmButtonText = '执行中...';
                    let {code,data} = await this.$Http.delStore({id:row.id})
                        if(code){
                            this.$message.success('删除成功!');
                            this.handleCurrentChange(1)
                        }
                        done();
                        instance.confirmButtonLoading = false;
                    } else {
                        done();
                    }
                }
            }).then(action => {

            }).catch(()=>{});
        }else if(type == 9){
            this.trademarkVisible = true
        } else {
          if (row.storeConfig) {
            this.form.wx_app_id = row.storeConfig.wx_app_id
            this.form.wx_app_secret = row.storeConfig.wx_app_secret
          }
          this.dialogFormVisible = true
        }
    },
    // 获取标签列表
    async GetList() {
      this.loading = true;
      this.paging.customize_id = localStorage.getItem('customize_id') || '' // 菜单customize_id
      let { code, data } = await this.$Http.getStore(this.paging);
      this.loading = false;
      if (code) {
        if (data.data.length) {
          data.data.forEach((ele) => {
            let end_time = ele.end_time.split(":");
            let start_time = ele.start_time.split(":");
            ele.end_time = end_time[0] + ":" + end_time[1];
            ele.start_time = start_time[0] + ":" + start_time[1];
          });
        }
        this.tableData = data.data;
        this.paging.limit = data.per_page;
        this.paging.total = data.total;
      }
    },
    reset() {
      //重置
      this.paging = this.$options.data().paging;
      this.GetList();
    },
  },
};
</script>

<style lang="scss" scoped>
.image-thumbnail {
  width: 130px;
  height: 130px;
}
.shopCs{
  color: rgb(24, 144, 255);
  text-decoration: underline;
  cursor: pointer;
}
.plImg{
  color: rgb(24, 144, 255);
  margin-top: 20px;
  cursor: pointer;
}
</style>